package org.example.chatservice.controller;

import lombok.RequiredArgsConstructor;
import org.example.chatservice.entity.ChatMessage;
import org.example.chatservice.entity.ChatRoom;
import org.example.chatservice.service.ChatService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class ChatController {
    private final ChatService chatService;

    @MessageMapping("/chat.private")
    public void processPrivateMessage(
            @Payload ChatMessage message,
            SimpMessageHeaderAccessor headerAccessor) {
        String senderId = headerAccessor.getUser().getName();
        message.setSenderId(senderId);
        chatService.sendPrivateMessage(message);
    }

    @MessageMapping("/chat.group")
    public void processGroupMessage(
            @Payload ChatMessage message,
            SimpMessageHeaderAccessor headerAccessor) {
        String senderId = headerAccessor.getUser().getName();
        message.setSenderId(senderId);
        chatService.sendGroupMessage(message);
    }

    @PostMapping("/api/chat/rooms")
    public ChatRoom createGroupChatRoom(
            @RequestBody ChatRoom chatRoom,
            @RequestHeader("X-User-ID") String userId) {
        return chatService.createGroupChatRoom(
            chatRoom.getName(),
            userId,
            chatRoom.getParticipants().stream().toList()
        );
    }

    @GetMapping("/api/chat/rooms")
    public List<ChatRoom> getUserChatRooms(@RequestHeader("X-User-ID") String userId) {
        return chatService.getUserChatRooms(userId);
    }

    @GetMapping("/api/chat/messages/{conversationId}")
    public List<ChatMessage> getConversationHistory(
            @PathVariable String conversationId,
            @RequestHeader("X-User-ID") String userId) {
        chatService.markMessagesAsRead(conversationId, userId);
        return chatService.getConversationHistory(conversationId);
    }
}